<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <UploadImg v-model="formData.avatar" height="80px" width="80px" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="用户类型" prop="userType">
            <el-radio-group v-model="formData.userType">
              <el-radio :label="1">直客</el-radio>
              <el-radio :label="2">渠道</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注"
              :rows="3"
            />
          </el-form-item>
        </el-tab-pane>
        
        <el-tab-pane label="安全设置" v-if="formType === 'create'">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </Dialog>
  
  <!-- 图片预览器 -->
  <el-image-viewer
    v-if="imageViewerVisible"
    @close="imageViewerVisible = false"
    :url-list="previewImages"
    :initial-index="previewIndex"
  />
</template>

<script setup lang="ts">
import { ref, reactive, computed, unref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { UserApi, type UserVO } from '@/api/weiyi/user'
import { useMessage } from '@/hooks/web/useMessage'

const emit = defineEmits(['success'])
const message = useMessage() // 消息提示

// 表单相关
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const formLoading = ref(false)
const formType = ref('') // create 或 update
const formData = ref<Partial<UserVO & { password?: string; confirmPassword?: string }>>({
  id: undefined,
  username: '',
  nickname: '',
  avatar: '',
  mobile: '',
  email: '',
  userType: 1,
  status: 0,
  remark: '',
  password: '',
  confirmPassword: ''
})

// 图片预览相关
const imageViewerVisible = ref(false)
const previewImages = ref<string[]>([])
const previewIndex = ref(0)

// 预览图片
const previewImage = (url: string) => {
  if (!url) {
    message.warning('请先输入图片URL')
    return
  }
  previewImages.value = [url]
  previewIndex.value = 0
  imageViewerVisible.value = true
}

// 表单标题
const dialogTitle = computed(() => {
  return formType.value === 'create' ? '新增用户' : '编辑用户'
})

// 表单校验规则
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: false, message: '请输入昵称', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号', 
      trigger: 'blur' 
    }
  ],
  email: [
    { 
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, 
      message: '请输入正确的邮箱地址', 
      trigger: 'blur' 
    }
  ],
  password: [
    { 
      required: true, 
      message: '请输入密码', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formType.value === 'create' && (!value || value.trim() === '')) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }
    },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { 
      required: true, 
      message: '请再次输入密码', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formType.value === 'create' && (!value || value.trim() === '')) {
          callback(new Error('请再次输入密码'))
        } else if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 打开表单
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()
  
  // 如果是编辑模式，需要获取详情
  if (type === 'update' && id) {
    try {
      formLoading.value = true
      formData.value = await UserApi.getUser(id)    
    } catch (error) {
      console.error('获取详情失败:', error)
      message.error('获取详情失败')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: undefined,
    username: '',
    nickname: '',
    avatar: '',
    mobile: '',
    email: '',
    userType: 1,
    status: 0, // 默认为正常状态
    remark: '',
    password: '',
    confirmPassword: ''
  }
  
  formRef.value?.resetFields()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    formLoading.value = true
    // 移除确认密码字段
    const { confirmPassword, ...submitData } = formData.value
    
    if (formType.value === 'create') {
      await UserApi.createUser(submitData as UserVO)
      message.success('新增成功')
    } else {
      // 编辑时移除密码字段
      const { password, ...updateData } = submitData
      await UserApi.updateUser(updateData as UserVO)
      message.success('修改成功')
    }
    
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== 'cancel') {
      message.error('表单提交失败')
    }
  } finally {
    formLoading.value = false
  }
}

// 导出方法供父组件调用
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.cursor-pointer {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
  }
}
</style> 